<?
if(!isset($_SESSION)){session_start();};
require_once("core.php");

$db->connectdb(DB_NAME,DB_USERNAME,DB_PASSWORD);

if($_POST['getsubcat']){

	$getsubcat = $db->select_query('SELECT * FROM subcat WHERE cat_id = '.$_POST['catid']);
	
	$msg = '<select id="subcat">';
	while($rs = $db->fetch($getsubcat)){
		$msg .= '<option value="'.$rs['sub_id'].'">'.$rs['sub_name'].'</option>';
	}
	$msg .= '</select>';
	echo $msg;
}

if($_POST['login']){
	$u = $_POST['user'];
	$p = md5($_POST['pwd']);
	$rm= $_POST['rem'];
	
	$q = $db->select_query('SELECT * FROM members WHERE username = "'.$u.'" AND password = "'.$p.'"');
	$rs = $db->fetch($q);
	$n = $db->rows($q);
	
	if($n > 0){
		$_SESSION['usr']	= $rs['username'];
		$_SESSION['ssid'] 	= session_id();
		$_SESSION['email']	= $rs['email'];
		if($rm == 'true'){
			$_SESSION['lifetime'] = 3600*24*365;
			setcookie('check_login',true,time()+(3600*24*365));
			$db->select_query('INSERT INTO session(ss_user,session,ss_ip,ss_endtime,ssdate) VALUES("'.$_SESSION['usr'].'","'.$_SESSION['ssid'].'","'.IPADDRESS.'","'.$_SESSION['lifetime'].'","'.time().'")');
		}else{
			$_SESSION['lifetime'] = 3600*24;
		}
		echo '{"status":"1","txt":"true"}';
	}else{
		echo '{"status":"0","txt":"false"}';
	}
	
}


if($_POST['checkcaptcha']){
	$c = $_POST['captcha'];
	$h = $_POST['chash'];
	if (rpHash($c) == $h) {
		echo '{"status":true}';
	}else{
		echo '{"status":false}';
	}
}

if($_POST['editprofile']){
	$field = $_POST['change_data'];
	$username = $_POST['username'];
	
	foreach($field as $field_name => $value){
		$db->update("members", $field_name.' = "'.$value.'"','username ="'.$username.'"');
	}
	echo '{"status":1}';
}

if($_POST['changepwd']){
	$opwd = $_POST['opwd'];
	$newpwd = $_POST['newpass'];
	$username = $_POST['uname'];
	
	$oldpass = $db->select_query('SELECT password FROM members WHERE username = "'.$username.'" AND password = "'.md5($opwd).'"');
	$rs = $db->fetch($oldpass);
	if(!empty($rs['password'])){
		$db->update("members", 'password = "'.md5($newpwd).'"','username ="'.$username.'"');
		echo '{"status":1}';
	}else{
		echo '{"status":0}';
	}
	//echo 'old = '.$opwd.'<br/>\n new = '.$newpwd.'<br/>\n username = '.$username;
}

if($_POST['post']){
	$data 	= $_POST['info'];
	$img 	= $_SESSION['img'];
	
	foreach($data as $field => $value){
		$f .= $field.',';
		$info .= '"'. $value .'", ';
		$update .= $field.'="'.$value.'",';	
	}
	foreach($img as $id => $name){
		$img_field .= 'img'.$id.',';
		$image .= '"'. $name .'", ';
		$imag_update .= 'img'.$id.'="'.$name.'",';
	}
	
	$pid = (isset($_POST['pid']) && $_POST['pid'] != "")? $_POST['pid']: genStr();
	$f = substr($f,0,strrpos($f,','));
	$info = substr($info,0,strrpos($info,','));	
	$update = substr($update,0,strrpos($update,','));
	
	if($_POST['post_status'] == true){
		$sql = 'UPDATE products SET '.$update.', p_update="'.time().'" WHERE pid = "'.$pid.'"';		
	}else{
		$sql = 'INSERT INTO products(pid,'.$f.') VALUES("'.$pid.'", '.$info.')';
	}
	
	if(mysql_query($sql)){
		$img_field = substr($img_field,0,strrpos($img_field,','));
		$updateimg = substr($imag_update,0,strrpos($imag_update,','));
		$image = '"'.$pid.'", '.substr($image,0,strrpos($image,','));
		$imgq = mysql_query('SELECT * FROM products_img WHERE pid = "'.$pid.'"')or die(mysql_error());
		
		$num = mysql_num_rows($imgq);
		
		if($num != "" && $num > 0){
			mysql_query('UPDATE products_img SET '.$updateimg.' WHERE pid = "'.$pid.'"')or die(__FILE__.__LINE__.mysql_error());
			unset($_SESSION['img']);
			echo '<meta HTTP-EQUIV="REFRESH" content="1; url='.WEB_URL.'/products/?m=products&p=product_detail&pid='.$pid.'">';
		}else{
			//mysql_query('INSERT INTO products_img(pid,'.$img_field.') VALUES('.$image.')')or die(__FILE__.' line = '.__LINE__.' Error = '.mysql_error());
			//echo 'INSERT INTO products_img(pid,'.$img_field.') VALUES('.$image.')';
			if(mysql_query('INSERT INTO products_img(pid,'.$img_field.') VALUES('.$image.')')){
				unset($_SESSION['img']);
				echo '<meta HTTP-EQUIV="REFRESH" content="1; url='.WEB_URL.'/products/?m=products&p=product_detail&pid='.$pid.'">';
			}else{
				//print_r($img);
				echo '0';
			}
		}
	}else{
		//mysql_query($sql)or die(__FILE__.' line = '.__LINE__.' Error = '.mysql_error());
		//echo $sql;
		echo '0';
	}

}

if($_POST['move_up']){
	$pid = $_POST['pid'];
	mysql_query('UPDATE products SET p_change_place = "'.time().'" WHERE pid ="'.$pid.'"')or die(__FILE__.' line = '.__LINE__.' Error = '.mysql_error());
	echo '{"status":1}';
}

if($_POST['delpost']){
	
	if($_POST['checkbox_name'] != ""){
		foreach ($_POST['checkbox_name'] as $checkbox_name)
		{
			$checkbox_name= htmlspecialchars($checkbox_name, ENT_QUOTES);
			mysql_query("DELETE FROM products WHERE pid = '".$checkbox_name."'");
	
		}
		$db->closedb();
		echo '{"status":"1"}';
	}
	
}

if($_POST['delimg']){
	$field = $_POST['field'];
	$url = str_replace('../','',$_POST['path']);
	$pid = $_POST['pid'];
	if(unlink($url)){
		if(mysql_query('UPDATE products_img SET '.$field.'="" WHERE pid="'.$pid.'"')){
			print '{"status":1,"txt":"Update Successfull!"}';
		}else{
			print '{"status":0,"txt":"Update Fail!!"}';
		}
	}else{
		echo '{"status":0, "txt":"'.unlink($url).'"}';
	}
}

//============================= Sticky Advertisment ==================
if($_POST['sticky_ads']){
	$pid 		= $_POST['pid'];
	$cid 		= $_POST['cid'];
	$pos 		= $_POST['position'];
	$period_time= ($_POST['period']>3)?$_POST['period']+1:$_POST['period'];
	$period		= ($period_time > 3)? $period_time-1: $period_time;
	$price 		= $_POST['price'];
	$discount 	= $_POST['discount'];
	$total 		= $_POST['total'];
	$id			= genStr();
	$addOrder	= addOrder($_SESSION['usr'],genStr(),$id.'#'.$pid,'sticky',IPADDRESS,'',$price,$discount,$total,time(),0);
	$q = mysql_query('INSERT INTO advertise(id,pid,cat_id,position_id,ads_period,ads_status,ads_price,ads_discount,ads_total,ads_expire) VALUES("'.$id.'","'.$pid.'",'.$cid.','.$pos.','.$period.',0,'.$price.','.$discount.','.$total.',"'.(time() + ($period_time*2419200)).'")')or die(mysql_error());
	
	if($q && $addOrder){
		echo '{"status":1}';
	}else{
		echo '{"status":0}';
	}
}

if($_POST['check_sticky']){
	$pid = $_POST['pid'];
	$q = mysql_query('SELECT * FROM advertise WHERE pid = "'.$pid.'"');
	$num = mysql_fetch_assoc($q);
	($num > 0)? print '{"status":1}': print '{"status":0}';
}

//============================= Banner Advertisment ==================
if($_POST['post_banner']){
	$username 	= $_POST['username'];
	$cat		= $_POST['category'];
	$pos		= $_POST['position'];
	$url		= $_POST['url'];
	$img		= $_POST['banner_img'];
	$period_time= ($_POST['banner_period']>6)? ($_POST['banner_period']+1) : $_POST['banner_period'];
	$period		= ($period_time > 4)? ($period_time-1) : $period_time;
	$size		= $_POST['banner_size'];
	$banner_id	= genStr();
	$price		= $_POST['pos_price'];
	$discount	= (!empty($_POST['discount'])? $_POST['discount']: 0 );
	$total		= (!empty($_POST['total'])? $_POST['total'] : ($discount != 0 ? $price - (($price*$discount)/100): $price));
	
	$get_banner	= mysql_query('SELECT * FROM banners WHERE url = "'.$img.'" AND position_id = '.$pos)or die(mysql_error());
	$has_banner	= mysql_num_rows($get_banner);

	$addOrder	= addOrder($username,genStr(),$banner_id,'banner',IPADDRESS,'',$price,$discount,$total,time(),0);
	if($has_banner == 0 || $has_banner == ''){
		$sql = 'INSERT INTO banners(user_id,banner_id,position_id,cat_id,url,image,size,period,create_at,banner_expire) VALUES("'.$username.'","'.$banner_id.'",'.$pos.','.$cat.',"'.$url.'","'.$img.'","'.$size.'",'.$period.',"'.time().'","'.(time() + ($period_time*2419200)).'")';
		
		if($addOrder && mysql_query($sql)){
			unset($_SESSION['banner_img']);
			echo '{"status":1}';
		}else{
			echo '{"status":0}';
		}
	}else{
		echo '{"status":"คุณไม่สามารถลงประกาศภาพเดียวกันในตำแหน่งเดียวกันซ้ำได้อีกคะ"}';
	}
}

if($_POST['get_pos_price']){
	$pos_name 	= $_POST['pos_name'];
	$q 		= mysql_query('SELECT price FROM positions WHERE position_name="'.$pos_name.'"')or die(mysql_error());
	$price 	= mysql_fetch_assoc($q);
	echo '{"status":1, "price":'.$price['price'].'}';
}

if($_POST['get_invoice_details']){
	$invoice = $_POST['inv'];
	$q = mysql_query('SELECT type,created_at,total FROM order_ads WHERE invoice = "'.$invoice.'"');
	$rs = mysql_fetch_assoc($q);
	echo '{"status":0, "details":["'.$rs['type'].'","'.ThaiTimeConvert($rs['created_at'],0,1).'","'.$rs['total'].'"]}';
}

if($_POST['order_confirm']){
	$invoice 	= $_POST['inv'];
	$type		= $_POST['type'];
	$date_saved = $_POST['date_saved'];
	$total_price= $_POST['total_price'];
	$transfer_price = $_POST['money_transfer'];
	$transfer_date	= $_POST['date_transfer'];
	$transfer_time	= $_POST['time_transfer'];
	$to_bank	= $_POST['to_bank'];
	$from_bank	= $_POST['from_bank'];
	$from_branch= $_POST['from_branch'];
	$detail		= $_POST['detail'];
	
	$confirmOrder = confirmOrder($invoice,$type,$date_saved,$total_price,$transfer_price,strtotime($transfer_date),$transfer_time,$to_bank,$from_bank,$from_branch,$detail);
	
	if($confirmOrder && mysql_query('UPDATE order_ads SET status=1 WHERE invoice="'.$invoice.'"')){
		echo '{"status":1}';
	}else{
		echo '{"status":0}';
	}
	
}


//======================== Random Product ID ==========================
function genStr() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = "";    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}
//addOrder($username='',$invioceID='',$type='',$ip='',$detail='',$price='',$discount='',$total='',$createAt='',$status=0);
function addOrder($username='',$invioceID='',$ads_id='',$type='',$ip='',$detail='',$price='',$discount='',$total='',$createAt='',$status=0){
	$order_sql = 'INSERT INTO order_ads(username,invoice,ads_id,type,ip,detail,price,discount,total,created_at,status)  VALUES("'.$username.'","'.$invioceID.'","'.$ads_id.'","'.$type.'","'.$ip.'","'.$detail.'","'.$price.'","'.$discount.'","'.$total.'","'.$createAt.'","'.$status.'")';
	if(mysql_query($order_sql)){
		return 'true';
	}else{
		return 'false';
	}
}
function confirmOrder($invoice='',$type='',$create_at='',$total_price='',$transfer_price='',$transfer_date='',$transfer_time='',$transfer_bank='',$from_bank='',$from_branch='',$detail=''){
	$confirm_sql = 'INSERT INTO order_confirm(invoice,type,created_at,total_price,transfer_price,transfer_date,transfer_time,transfer_bank,from_bank,from_branch,detail)  VALUES("'.$invoice.'","'.$type.'","'.$create_at.'","'.$total_price.'","'.$transfer_price.'","'.$transfer_date.'","'.$transfer_time.'","'.$transfer_bank.'","'.$from_bank.'","'.$from_branch.'","'.$detail.'")';
	if(mysql_query($confirm_sql)){
		return 'true';
	}else{
		return 'false';
	}
}
?>